package org.jeecg.modules.tplus.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstants;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.RedisConstant;
import org.jeecg.common.constant.enums.TPlusToEz2bizEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.*;
import org.jeecg.modules.goods.goods.entity.Goods;
import org.jeecg.modules.goods.goodsadjust.entity.CgGoodsAdjust;
import org.jeecg.modules.goods.goodsadjust.service.ICgGoodsAdjustService;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.entity.SysDict;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.tplus.dto.*;
import org.jeecg.modules.tplus.service.ITplusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: t+接口管理
 * @Author: jeecg-boot
 * @Date: 2025-06-07
 * @Version: V1.0
 */
@Slf4j
@Service
public class TplusServiceImpl implements ITplusService {
    @Value("${chanjet.openapi.gatewayUrl}")
    private String T_PLUS_URL;
    @Value("${ez2bz.api.url}")
    private String API_TOKEN_URL;
    @Value("${chanjet.openapi.appKey}")
    private String OPENAPI_APPKEY;
    @Value("${chanjet.openapi.appSecret}")
    private String OPENAPI_APPSECRET;

    @Autowired
    private RedisUtil redisUti;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ISysDictItemService sysDictItemService;
    @Autowired
    private org.jeecg.modules.system.service.ISysCategoryService sysCategoryService;
    @Autowired
    private ICgGoodsAdjustService cgGoodsAdjustService;

    @Autowired
    @Lazy
    private org.jeecg.modules.goods.goods.service.IGoodsService goodsService;

    @Override
    public void getInventoryByTPlus(String startDate, String endDate, String code, String classCode) {
        // 1、根据日期查询这段时间内的T+存货信息
        InventoryQueryReqDto.InventoryQueryParam param = new InventoryQueryReqDto.InventoryQueryParam();
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            startDate = DateFormatUtils.format(DateFormatUtils.beginOfDay(new Date()),
                    DateFormatUtils.DEFAULT_TIME_PATTERN);
            endDate = DateFormatUtils.format(DateFormatUtils.endOfDay(new Date()),
                    DateFormatUtils.DEFAULT_TIME_PATTERN);
        }
        if (StringUtils.isNotBlank(code)) {
            param.setCode(code);
        }
        if (StringUtils.isNotBlank(classCode)) {
            InventoryQueryReqDto.InventoryQueryParam.InventoryClass inventoryClass = new InventoryQueryReqDto.InventoryQueryParam.InventoryClass();
            inventoryClass.setCode(classCode);
            param.setInventoryClass(inventoryClass);
        }
        param.setUpdateDateBegin(startDate);
        param.setUpdateDateEnd(endDate);
        createInventoryByTPlus(param);
    }

    public void createInventoryByTPlus(InventoryQueryReqDto.InventoryQueryParam param) {
        // TODO: 需要从GoodsServiceImpl中获取商品列表
        List<Goods> plusInventories = new ArrayList<>();
        createOrUpdateInventoryByTPlus(param, plusInventories);
    }

    /**
     * 递归调用创建或更新存货信息
     *
     * @param param           存货查询参数
     * @param plusInventories 存货信息
     */
    private void createOrUpdateInventoryByTPlus(InventoryQueryReqDto.InventoryQueryParam param,
            List<Goods> plusInventories) {
        InventoryQueryReqDto inventoryQuery = new InventoryQueryReqDto();
        inventoryQuery.setParam(param);
        // 查询存货信息
        InventoryListQueryRepDto inventoryListQueryRepDto = doInventoryQuery(inventoryQuery);
        if (inventoryListQueryRepDto == null || CollectionUtils.isEmpty(inventoryListQueryRepDto.getData())) {
            return;
        }
        List<InventoryQueryRepDto> inventoryQueryRepDtos = inventoryListQueryRepDto.getData();
        List<InventoryQueryRepDto> inventoryQueryRepDtoList = new ArrayList<>();
        for (InventoryQueryRepDto entity : inventoryQueryRepDtos) {
            InventoryQueryRepDto inventoryQueryRepDto1;
            try {
                // 处理自定义字段的赋值
                inventoryQueryRepDto1 = BeanUtils.mapArrayToObject(entity.getDynamicPropertyKeys(),
                        entity.getDynamicPropertyValues(), entity);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                continue;
            }
            inventoryQueryRepDtoList.add(inventoryQueryRepDto1);
        }

        // 将T+存货信息保存到cg_goods表
        for (InventoryQueryRepDto inventoryDto : inventoryQueryRepDtoList) {
            try {
                // 调用GoodsServiceImpl的saveInventoryFromTPlus方法保存存货信息
                goodsService.saveInventoryFromTPlus(inventoryDto, "system");
                log.info("成功保存T+存货信息: 编码={}, 名称={}", inventoryDto.getCode(), inventoryDto.getName());
            } catch (Exception e) {
                log.error("保存T+存货信息失败: 编码={}, 错误信息={}", inventoryDto.getCode(), e.getMessage(), e);
            }
        }
        // 翻页
        if (inventoryListQueryRepDto.getCurrentPage() <= inventoryListQueryRepDto.getTotalPage()) {
            param.setPageIndex(inventoryListQueryRepDto.getCurrentPage() + 1);
            createOrUpdateInventoryByTPlus(param, plusInventories);
        }
    }

    /**
     * 获取存货信息列表
     *
     * @param inventoryQuery 存货查询信息
     * @return 存货信息列表
     */
    @Override
    public InventoryListQueryRepDto doInventoryQuery(InventoryQueryReqDto inventoryQuery) {
        InventoryListQueryRepDto inventoryListQueryRepDto = new InventoryListQueryRepDto();
        InventoryQueryReqDto.InventoryQueryParam param = inventoryQuery.getParam();
        if (StringUtils.isBlank(param.getSelectFields())) {
            List<String> selectFields = ReflectUtils.getFieldsByAnnotation(InventoryQueryRepDto.class);
            param.setSelectFields(String.join(",", selectFields));
        }
        String postUrl = T_PLUS_URL + "/tplus/api/v2/inventory/QueryPage";
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(inventoryQuery), initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
            // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
            try {
                inventoryListQueryRepDto = JsonUtils.json2bean(result, InventoryListQueryRepDto.class);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return null;
            }
        }
        return inventoryListQueryRepDto;
    }

    /**
     * 查询计量单位
     *
     * @param unitQueryReqDto 查询计量单位
     * @return 查询计量单位
     */
    @Override
    public UnitQueryRepDto unitQuery(UnitQueryReqDto unitQueryReqDto) {
        UnitQueryRepDto unitQueryRepDto = new UnitQueryRepDto();
        String postUrl = T_PLUS_URL + "/tplus/api/v2/Unit/Query";
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(unitQueryReqDto), initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
            // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
            try {
                unitQueryRepDto = JsonUtils.json2bean(result, UnitQueryRepDto.class);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return null;
            }
        }
        return unitQueryRepDto;
    }

    /**
     * 创建存货信息
     *
     * @param inventoryInfoReqDto 存货信息
     * @return 结果
     */
    @Override
    public InventoryInfoRepDto inventoryCreate(InventoryInfoReqDto inventoryInfoReqDto) {
        InventoryInfoRepDto repDto = new InventoryInfoRepDto();
        String postUrl = T_PLUS_URL + "/tplus/api/v2/inventory/Create";
        // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
        // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(inventoryInfoReqDto), initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            if (!Objects.equals(result, "null")) {
                Map<String, Object> map = JsonUtils.json2Map(result);
                if (map.get("code") != null && !map.get("code").equals(200)) {
                    throw new JeecgBootException(map.get("message").toString());
                }
            }
        } else {
            throw new JeecgBootException("新增存货信息失败");
        }
        return repDto;
    }

    /**
     * 更新存货信息
     *
     * @param inventoryInfoReqDto 存货信息
     * @return 结果
     */
    @Override
    public InventoryInfoRepDto inventoryUpdate(InventoryInfoReqDto inventoryInfoReqDto) {
        InventoryInfoRepDto repDto = new InventoryInfoRepDto();
        String postUrl = T_PLUS_URL + "/tplus/api/v2/inventory/Update";
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(inventoryInfoReqDto), initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
            // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
            if (!Objects.equals(result, "true")) {
                Map<String, Object> map = JsonUtils.json2Map(result);
                if (map.get("code") != null && !map.get("code").equals(200)) {
                    throw new JeecgBootException(map.get("message").toString());
                }
            }
        } else {
            throw new JeecgBootException("更新存货信息失败");
        }
        return repDto;
    }

    @Override
    public InventoryInfoRepDto updateImage(InventoryImageEntityReqDto inventoryImageEntityReqDto) {
        InventoryImageReqDto imageDto = new InventoryImageReqDto();
        imageDto.setInventoryEntityReqDto(inventoryImageEntityReqDto);
        InventoryInfoRepDto repDto = new InventoryInfoRepDto();
        String postUrl = T_PLUS_URL + "/tplus/api/v2/inventory/UpdateImage";
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(imageDto),
                initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
            // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
            if (!Objects.equals(result, "true")) {
                Map<String, Object> map = JsonUtils.json2Map(result);
                if (map.get("code") != null && !map.get("code").equals(200)) {
                    throw new JeecgBootException(map.get("message").toString());
                }
            }
        } else {
            throw new JeecgBootException("更新存货信息失败");
        }
        return repDto;
    }

    @Override
    public void handleEnum() {
        for (TPlusToEz2bizEnum tPlusToEz2bizEnum : TPlusToEz2bizEnum.values()) {
            QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SysDict::getDictName, tPlusToEz2bizEnum.getTPlusEnumName());
            SysDict sysDict = sysDictService.getOne(queryWrapper);
            if (sysDict == null) {
                continue;
            }
            List<SysDictItem> sysDictItems = sysDictItemService
                    .list(new QueryWrapper<SysDictItem>().lambda().eq(SysDictItem::getDictId, sysDict.getId()));
            if (CollectionUtil.isNotEmpty(sysDictItems)) {
                sysDictItemService.removeBatchByIds(sysDictItems);
            }
            EnumQueryRepDto enumQueryRepDto = getEnumByName(new EnumQueryReqDto(tPlusToEz2bizEnum.getTPlusEnumName()));
            if (enumQueryRepDto == null || enumQueryRepDto.getData() == null) {
                continue;
            }
            List<EnumQueryRepDto.EnumItem> enumItemList = enumQueryRepDto.getData().getEnumItemList();
            if (CollectionUtil.isNotEmpty(enumItemList)) {
                for (EnumQueryRepDto.EnumItem enumItem : enumItemList) {
                    SysDictItem sysDictItem = new SysDictItem();
                    sysDictItem.setDictId(sysDict.getId());
                    sysDictItem.setItemText(enumItem.getName());
                    sysDictItem.setItemValue(enumItem.getCode());
                    sysDictItemService.save(sysDictItem);
                }
            }
        }
    }

    @Override
    public EnumQueryRepDto getEnumByName(EnumQueryReqDto enumQueryReqDto) {
        EnumQueryRepDto enumQueryRepDto = new EnumQueryRepDto();
        String postUrl = T_PLUS_URL + "/tplus/api/v2/EnumRest/GetEnumByTitle";
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(enumQueryReqDto), initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
            // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
            try {
                enumQueryRepDto = JsonUtils.json2bean(result, EnumQueryRepDto.class);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return null;
            }
        }
        return enumQueryRepDto;
    }

    /**
     * 获取仓库列表
     *
     * @param warehouseQueryReqDto 仓库查询信息
     * @return 仓库信息列表
     */
    @Override
    public List<WarehouseQueryRepDto> warehouseQuery(WarehouseQueryReqDto warehouseQueryReqDto) {
        List<WarehouseQueryRepDto> warehouseListQueryRepDto = new ArrayList<>();
        WarehouseQueryReqDto.WarehouseQueryParam param = warehouseQueryReqDto.getParam();
        if (StringUtils.isBlank(param.getSelectFields())) {
            List<String> selectFields = ReflectUtils.getFieldsByAnnotation(WarehouseQueryRepDto.class);
            param.setSelectFields(String.join(",", selectFields));
        }
        String postUrl = T_PLUS_URL + "/tplus/api/v2/warehouse/Query";
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(warehouseQueryReqDto), initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
            // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
            try {
                warehouseListQueryRepDto = JsonUtils.json2List(result, WarehouseQueryRepDto.class);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return null;
            }
        }
        return warehouseListQueryRepDto;
    }

    /**
     * 获取货位列表
     *
     * @param invLocationQueryReqDto 获取货位列表
     * @return 货位信息列表
     */
    @Override
    public List<InvLocationQueryRepDto> invLocationQuery(InvLocationQueryReqDto invLocationQueryReqDto) {
        List<InvLocationQueryRepDto> invLocationQueryRepDtos = new ArrayList<>();
        InvLocationQueryReqDto.InvLocationQueryParam param = invLocationQueryReqDto.getParam();
        if (StringUtils.isBlank(param.getSelectFields())) {
            List<String> selectFields = ReflectUtils.getFieldsByAnnotation(InvLocationQueryRepDto.class);
            param.setSelectFields(String.join(",", selectFields));
        }
        String postUrl = T_PLUS_URL + "/tplus/api/v2/invLocation/Query";
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(invLocationQueryReqDto), initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
            // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
            try {
                invLocationQueryRepDtos = JsonUtils.json2List(result, InvLocationQueryRepDto.class);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return null;
            }
        }
        return invLocationQueryRepDtos;
    }

    /**
     * 获取存货分类列表
     *
     * @param inventoryClassQueryReqDto 存货分类信息
     * @return 存货分类信息列表
     */
    @Override
    public List<InventoryClassQueryRepDto> inventoryClassQuery(InventoryClassQueryReqDto inventoryClassQueryReqDto) {
        List<InventoryClassQueryRepDto> inventoryClassQueryRepDtos = new ArrayList<>();
        InventoryClassQueryReqDto.InventoryClassQueryParam param = inventoryClassQueryReqDto.getParam();
        if (StringUtils.isBlank(param.getSelectFields())) {
            List<String> selectFields = ReflectUtils.getFieldsByAnnotation(InventoryClassQueryRepDto.class);
            param.setSelectFields(String.join(",", selectFields));
        }
        String postUrl = T_PLUS_URL + "/tplus/api/v2/inventoryClass/Query";
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(inventoryClassQueryReqDto), initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
            // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
            try {
                inventoryClassQueryRepDtos = JsonUtils.json2List(result, InventoryClassQueryRepDto.class);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return null;
            }
        }
        return inventoryClassQueryRepDtos;
    }

    /**
     * 查询往来单位信息
     *
     * @param partnerQueryReqDto 往来单位查询参数
     * @return 往来单位信息
     */
    @Override
    public List<PartnerQueryRepDto> doPartnerQuery(PartnerQueryReqDto partnerQueryReqDto) {
        List<PartnerQueryRepDto> partnerListQueryRepDto = new ArrayList<>();
        PartnerQueryReqDto.PartnerQueryParam param = partnerQueryReqDto.getParam();
        if (StringUtils.isBlank(param.getSelectFields())) {
            List<String> selectFields = ReflectUtils.getFieldsByAnnotation(PartnerQueryFieldRepDto.class);
            param.setSelectFields(String.join(",", selectFields));
        }
        String postUrl = T_PLUS_URL + "/tplus/api/v2/partner/Query";
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(partnerQueryReqDto), initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
            // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
            try {
                partnerListQueryRepDto = JsonUtils.json2List(result, PartnerQueryRepDto.class);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return null;
            }
        }
        return partnerListQueryRepDto;
    }

    /**
     * 初始化请求头
     *
     * @return 请求头
     */
    private HashMap<String, String> initRequestToken() {
        String tPlusToken = (String) redisUti.get(RedisConstant.T_PLUS_TOKEN);
        if (StringUtils.isBlank(tPlusToken)) {
            getToken(new RefreshTokenReqDto());
            tPlusToken = (String) redisUti.get(RedisConstant.T_PLUS_TOKEN);
        }
        HashMap<String, String> map = new HashMap<>();
        map.put(CommonConstants.APPKEY, OPENAPI_APPKEY);
        map.put(CommonConstants.APPSECRET, OPENAPI_APPSECRET);
        map.put(CommonConstants.OPENTOKEN, tPlusToken);
        return map;
    }

    @Override
    public void getToken(RefreshTokenReqDto refreshTokenReqDto) {
        String result = HttpUtils.sendPost(API_TOKEN_URL, convert(refreshTokenReqDto),
                "application/x-www-form-urlencoded", null);
        if (StringUtils.isNotBlank(result)) {
            GetTokenRepDto refreshTokenRepDto = JsonUtils.json2bean(result, GetTokenRepDto.class);
            if (refreshTokenRepDto == null || !refreshTokenRepDto.isSuccess()) {
                throw new JeecgBootException("获取token失败");
            }
            redisUti.set(RedisConstant.T_PLUS_TOKEN, refreshTokenRepDto.getMsg());
        }
    }

    @Override
    public void createDictByEnumName(String tPlusEnumName) {
        try {
            // 根据tPlusEnumName获取对应的枚举
            TPlusToEz2bizEnum enumItem = TPlusToEz2bizEnum.getCurrency(tPlusEnumName);
            if (enumItem == null) {
                throw new JeecgBootException("未找到对应的枚举: " + tPlusEnumName);
            }

            // 检查字典是否已存在
            QueryWrapper<SysDict> dictQuery = new QueryWrapper<>();
            dictQuery.eq("dict_code", enumItem.getEnumCode());
            SysDict sysDict = sysDictService.getOne(dictQuery);

            if (sysDict == null) {
                sysDict = new SysDict();
                sysDict.setDictName(enumItem.getEnumName());
                sysDict.setDictCode(enumItem.getEnumCode());
                sysDict.setDescription("T+枚举: " + enumItem.getEnumName());
                sysDict.setDelFlag(CommonConstant.DEL_FLAG_0);
                sysDict.setCreateTime(new Date());
                sysDictService.save(sysDict);
            }

            // 从T+获取枚举数据
            EnumQueryReqDto enumQueryReqDto = new EnumQueryReqDto(tPlusEnumName);
            EnumQueryRepDto enumData = getEnumByName(enumQueryReqDto);

            // 创建字典项
            if (enumData != null && enumData.getData() != null
                    && CollectionUtils.isNotEmpty(enumData.getData().getEnumItemList())) {
                List<SysDictItem> sysDictItems = sysDictItemService
                        .list(new QueryWrapper<SysDictItem>().lambda().eq(SysDictItem::getDictId, sysDict.getId()));
                if (CollectionUtil.isNotEmpty(sysDictItems)) {
                    sysDictItemService.removeBatchByIds(sysDictItems);
                }
                List<SysDictItem> dictItems = new ArrayList<>();
                for (EnumQueryRepDto.EnumItem item : enumData.getData().getEnumItemList()) {
                    SysDictItem dictItem = new SysDictItem();
                    dictItem.setDictId(sysDict.getId());
                    dictItem.setItemText(item.getName());
                    dictItem.setItemValue(item.getCode());
                    dictItem.setDescription("T+枚举项");
                    dictItem.setSortOrder(1);
                    dictItem.setStatus(1);
                    dictItem.setCreateTime(new Date());
                    dictItems.add(dictItem);
                }
                sysDictItemService.saveBatch(dictItems);
            }

            // 处理分类逻辑：根据categoryCode是否有值来处理sys_category
            if (StringUtils.isNotBlank(enumItem.getCategoryCode())) {
                handleCategoryLogic(enumItem.getCategoryCode(), enumData, tPlusEnumName);
            }

        } catch (Exception e) {
            throw new JeecgBootException("创建字典失败: " + e.getMessage());
        }
    }

    public static String convert(Object object) {
        StringBuilder params = new StringBuilder();
        try {
            for (Field field : object.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                String name = field.getName();
                JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
                if (jsonProperty != null) {
                    name = jsonProperty.value();
                }
                Object value = field.get(object);
                if (value != null) {
                    String encodedValue = value.toString();
                    params.append(name).append("=").append(URLEncoder.encode(encodedValue, StandardCharsets.UTF_8))
                            .append("&");
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        params.deleteCharAt(params.length() - 1);
        return params.toString();
    }

    /**
     * 处理分类逻辑：根据categoryCode查询sys_category，不存在则新增，存在则删除子级后重新添加
     * @param categoryCode 分类编码
     * @param enumData 枚举数据
     * @param tPlusEnumName T+枚举名称
     */
    private void handleCategoryLogic(String categoryCode, EnumQueryRepDto enumData, String tPlusEnumName) {
        try {
            // 根据categoryCode查询sys_category是否存在
            String categoryId = sysCategoryService.queryIdByCode(categoryCode);

            org.jeecg.modules.system.entity.SysCategory parentCategory;
            if (StringUtils.isBlank(categoryId)) {
                // 不存在则新增父级分类
                parentCategory = new org.jeecg.modules.system.entity.SysCategory();
                parentCategory.setName(tPlusEnumName + "分类");
                parentCategory.setCode(categoryCode);
                parentCategory.setPid(org.jeecg.modules.system.service.ISysCategoryService.ROOT_PID_VALUE);
                parentCategory.setHasChild("1");
                parentCategory.setCreateTime(new Date());
                sysCategoryService.save(parentCategory);
                categoryId = parentCategory.getId();
            } else {
                // 存在则先删除该分类下的所有子级分类
                parentCategory = sysCategoryService.getById(categoryId);
                if (parentCategory != null) {
                    // 查询并删除所有子级分类
                    QueryWrapper<SysCategory> childQuery =
                        new QueryWrapper<>();
                    childQuery.eq("pid", categoryId);
                    List<SysCategory> childCategories = sysCategoryService.list(childQuery);
                    if (CollectionUtil.isNotEmpty(childCategories)) {
                        List<String> childIds = childCategories.stream()
                            .map(SysCategory::getId)
                            .collect(java.util.stream.Collectors.toList());
                        sysCategoryService.removeByIds(childIds);
                    }
                }
            }

            // 根据枚举数据新增子级分类
            if (enumData != null && enumData.getData() != null
                && CollectionUtils.isNotEmpty(enumData.getData().getEnumItemList())) {
                List<SysCategory> childCategories = new ArrayList<>();
                for (EnumQueryRepDto.EnumItem item : enumData.getData().getEnumItemList()) {
                    SysCategory childCategory = new SysCategory();
                    childCategory.setName(item.getName());
                    // 使用父级code + 枚举项code作为子级code
                    childCategory.setCode(item.getCode());
                    childCategory.setPid(categoryId);
                    childCategory.setHasChild("0");
                    childCategory.setCreateTime(new Date());
                    childCategories.add(childCategory);
                }
                sysCategoryService.saveBatch(childCategories);
            }

        } catch (Exception e) {
            log.error("处理分类逻辑失败: {}", e.getMessage(), e);
            throw new JeecgBootException("处理分类逻辑失败: " + e.getMessage());
        }
    }

    /**
     * 同步存货分类到系统分类
     * 根据分类字典编码C06进行处理：如果不存在则新增分类字典，如果存在则先删除原有子项，然后将查询分类接口的数据作为新的子分类添加
     */
    @Override
    public void syncInventoryClassToCategory() {
        try {
            String categoryCode = "C06";

            // 1. 查询T+存货分类数据(所有分类)
            List<InventoryClassQueryRepDto> inventoryClassList = inventoryClassQuery(new InventoryClassQueryReqDto());

            if (CollectionUtils.isEmpty(inventoryClassList)) {
                log.warn("未查询到T+存货分类数据");
                return;
            }

            // 2. 检查系统分类表中是否存在C06分类
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<org.jeecg.modules.system.entity.SysCategory> query =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            query.eq("code", categoryCode);
            org.jeecg.modules.system.entity.SysCategory parentCategory = sysCategoryService.getOne(query);

            String categoryId;
            if (parentCategory == null) {
                // 3. 不存在则新增C06分类
                org.jeecg.modules.system.entity.SysCategory newCategory = new org.jeecg.modules.system.entity.SysCategory();
                newCategory.setName("存货分类");
                newCategory.setCode(categoryCode);
                newCategory.setPid("0"); // 顶级分类
                newCategory.setHasChild("1"); // 有子级
                newCategory.setCreateTime(new Date());
                sysCategoryService.save(newCategory);
                categoryId = newCategory.getId();
                log.info("新增系统分类: {}", categoryCode);
            } else {
                categoryId = parentCategory.getId();
                // 4. 存在则递归删除当前分类的所有后代（直接子级及其子级）
                List<org.jeecg.modules.system.entity.SysCategory> allCategories = sysCategoryService.list();
                java.util.Set<String> deleteIds = new java.util.HashSet<>();
                java.util.Deque<String> queue = new java.util.ArrayDeque<>();
                queue.add(categoryId);
                while (!queue.isEmpty()) {
                    String pid = queue.poll();
                    for (org.jeecg.modules.system.entity.SysCategory c : allCategories) {
                        if (pid.equals(c.getPid())) {
                            if (deleteIds.add(c.getId())) {
                                queue.add(c.getId());
                            }
                        }
                    }
                }
                if (!deleteIds.isEmpty()) {
                    sysCategoryService.removeByIds(deleteIds);
                    log.info("递归删除当前分类的后代数量: {}", deleteIds.size());
                } else {
                    log.info("未发现需要删除的后代分类，跳过删除");
                }
                parentCategory.setHasChild("1");
                sysCategoryService.updateSysCategory(parentCategory);
            }

            // 5. 构建分类映射关系，用于查找父级分类
            Map<String, org.jeecg.modules.system.entity.SysCategory> categoryMap = new HashMap<>();

            // 按照是否有父级分类进行排序，确保父级分类先处理
            inventoryClassList.sort((a, b) -> {
                if (StringUtils.isBlank(a.getParentCode()) && StringUtils.isNotBlank(b.getParentCode())) {
                    return -1;
                }
                if (StringUtils.isNotBlank(a.getParentCode()) && StringUtils.isBlank(b.getParentCode())) {
                    return 1;
                }
                return 0;
            });

            // 6. 根据T+存货分类数据新增子级分类
            List<org.jeecg.modules.system.entity.SysCategory> childCategories = new ArrayList<>();
            for (InventoryClassQueryRepDto item : inventoryClassList) {
                org.jeecg.modules.system.entity.SysCategory childCategory = new org.jeecg.modules.system.entity.SysCategory();
                childCategory.setId(item.getCode()); // 使用T+分类的code作为系统分类的ID
                childCategory.setName(item.getName());
                childCategory.setCode(item.getCode()); // 使用T+分类编码作为系统分类编码

                // 根据parentCode查找父级分类，如果找不到则使用根分类
                if (StringUtils.isNotBlank(item.getParentCode())) {
                    org.jeecg.modules.system.entity.SysCategory parent = categoryMap.get(item.getParentCode());
                    if (parent != null) {
                        childCategory.setPid(parent.getId());
                    } else {
                        childCategory.setPid(categoryId); // 默认使用C06作为父级
                    }
                } else {
                    childCategory.setPid(categoryId); // 顶级分类，使用C06作为父级
                }

                // 根据isendnode判断是否有子级
                childCategory.setHasChild(item.isIsendnode() ? "0" : "1");
                childCategory.setCreateTime(new Date());

                childCategories.add(childCategory);
                categoryMap.put(item.getCode(), childCategory);
            }

            if (CollectionUtil.isNotEmpty(childCategories)) {
                sysCategoryService.saveBatch(childCategories);
                log.info("同步存货分类到系统分类完成，新增子分类数量: {}", childCategories.size());
            }

        } catch (Exception e) {
            log.error("同步存货分类到系统分类失败: {}", e.getMessage(), e);
            throw new JeecgBootException("同步存货分类失败: " + e.getMessage());
        }
    }

    /**
     * 递归获取子级存货分类
     * @param parentCode 父级分类编码
     * @param resultList 结果列表
     */
    private void fetchChildInventoryClasses(String parentCode, List<InventoryClassQueryRepDto> resultList) {
        /*try {
            // 构造查询条件，查询指定父级编码的子分类
            InventoryClassQueryReqDto reqDto = new InventoryClassQueryReqDto();
            reqDto.setParam(new InventoryClassQueryReqDto.InventoryClassQueryParam());
            reqDto.getParam().setParentCode(parentCode);

            List<InventoryClassQueryRepDto> childList = inventoryClassQuery(reqDto);

            if (CollectionUtils.isNotEmpty(childList)) {
                resultList.addAll(childList);

                // 递归获取下级分类
                for (InventoryClassQueryRepDto child : childList) {
                    if (!child.isIsendnode()) {
                        // 如果不是末级节点，继续查询其子级
                        fetchChildInventoryClasses(child.getCode(), resultList);
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取子级存货分类失败，父级编码: {}", parentCode, e);
        }*/
    }
    //单据编号
    //单据日期

    //存货编码
    //存货编码
    //
    //存货名称
    //存货名称

    //七级批发价
    //香港利润率

//八级批发价
//大陆利润率
    //调前九级批发价
    //调前香港成本
    //
    //九级批发价
    //香港成本
    //
    //调前十级批发价
    //调前大陆成本
    //
    //十级批发价
    //大陆成本

    @Override
    public void createInventoryAdjustPriceByTPlus(InventoryAdjustPriceQueryReqDto inventoryAdjustPriceQueryReqDto) {
        Map<String, String> orders = new HashMap<>();
        List<CgGoodsAdjust> plusSaleOrders = cgGoodsAdjustService.list();
        createOrUpdateInventoryAdjustPriceByTPlus(inventoryAdjustPriceQueryReqDto, plusSaleOrders, orders);
    }

    private void createOrUpdateInventoryAdjustPriceByTPlus(InventoryAdjustPriceQueryReqDto inventoryAdjustPriceQueryReqDto, List<CgGoodsAdjust> plusSaleOrders, Map<String, String> orders) {
        // 查询销售订单信息
        InventoryAdjustPriceQueryRepDto inventoryAdjustPriceQueryRepDtos = inventoryAdjustPriceQuery(inventoryAdjustPriceQueryReqDto);
        if (inventoryAdjustPriceQueryRepDtos == null || CollectionUtils.isEmpty(inventoryAdjustPriceQueryRepDtos.getRows())) {
            return;
        }

        List<List<Object>> rows = inventoryAdjustPriceQueryRepDtos.getRows();
        // 遍历销售出库单信息
        for (List<Object> objects : rows) {
            // 处理销售订单信息
            InventoryAdjustPriceRepDto saleOrderInfoRepDto = new InventoryAdjustPriceRepDto();
            try {
                BeanUtils.mapArrayToObject(inventoryAdjustPriceQueryRepDtos.getColumns().toArray(), objects.toArray(), saleOrderInfoRepDto);
            } catch (IllegalAccessException e) {
                throw new JeecgBootException(e);
            }

            // 判断已更新的数据才入库(已更新)
            if (!Objects.equals(saleOrderInfoRepDto.getIsupdatepricebook_code(), "02")) {
                continue;
            }

            // 判断这个订单是不是已经在数据库中存在了，存在了就不在创建
            CgGoodsAdjust oldOrder = plusSaleOrders.stream().filter(plusDeliveryOrder -> plusDeliveryOrder.getDetailsId().equals(saleOrderInfoRepDto.getInventoryadjustpricedetails_id())).findFirst().orElse(null);
            if (oldOrder != null) {
                continue;
            }

            // 判断订单主信息是否已新增
            if (!orders.containsKey(saleOrderInfoRepDto.getInventoryadjustpricedetails_id())) {
                // 如果主订单未新增则新增主订单
                CgGoodsAdjust plusOrder = new CgGoodsAdjust();
                plusOrder.setCode(saleOrderInfoRepDto.getCode());
                plusOrder.setVoucherDate(saleOrderInfoRepDto.getVoucherdate());
                plusOrder.setName(saleOrderInfoRepDto.getName());
                plusOrder.setIsupdatepricebookCode(saleOrderInfoRepDto.getIsupdatepricebook_code());
                plusOrder.setAuditedtime(saleOrderInfoRepDto.getAuditedtime());
                plusOrder.setDetailsId(saleOrderInfoRepDto.getInventoryadjustpricedetails_id());
                plusOrder.setInventoryCode(saleOrderInfoRepDto.getInventoryadjustpricedetails_inventory_code());
                plusOrder.setInventoryName(saleOrderInfoRepDto.getInventoryadjustpricedetails_inventory_name());
                plusOrder.setInvscost7formula(saleOrderInfoRepDto.getInventoryadjustpricedetails_invscost7formula());
                plusOrder.setInvscost8formula(saleOrderInfoRepDto.getInventoryadjustpricedetails_invscost8formula());
                plusOrder.setBeforeinvscost9formula(saleOrderInfoRepDto.getInventoryadjustpricedetails_beforeinvscost9formula());
                plusOrder.setInvscost9formula(saleOrderInfoRepDto.getInventoryadjustpricedetails_invscost9formula());
                plusOrder.setBeforeinvscost10formula(saleOrderInfoRepDto.getInventoryadjustpricedetails_beforeinvscost10formula());
                plusOrder.setInvscost10formula(saleOrderInfoRepDto.getInventoryadjustpricedetails_invscost10formula());
                cgGoodsAdjustService.save(plusOrder);
                orders.put(saleOrderInfoRepDto.getInventoryadjustpricedetails_id(), plusOrder.getId());
                plusSaleOrders.add(plusOrder);
            }
        }
        // 递归查询下一页
        inventoryAdjustPriceQueryReqDto.setPageIndex(inventoryAdjustPriceQueryReqDto.getPageIndex() + 1);
        createOrUpdateInventoryAdjustPriceByTPlus(inventoryAdjustPriceQueryReqDto, plusSaleOrders, orders);
    }

    @Override
    public List<InventoryAdjustPriceRepDto> inventoryAdjustPriceQueryByHandle(InventoryAdjustPriceQueryReqDto inventoryAdjustPriceQueryReqDto) {
        List<InventoryAdjustPriceRepDto> inventoryAdjustPriceRepDtos = new ArrayList<>();
        InventoryAdjustPriceQueryRepDto inventoryAdjustPriceQueryRepDtos = inventoryAdjustPriceQuery(inventoryAdjustPriceQueryReqDto);
        if (inventoryAdjustPriceQueryRepDtos == null || CollectionUtils.isEmpty(inventoryAdjustPriceQueryRepDtos.getRows())) {
            return inventoryAdjustPriceRepDtos;
        }
        List<List<Object>> rows = inventoryAdjustPriceQueryRepDtos.getRows();
        // 遍历销售出库单信息
        for (List<Object> objects : rows) {
            // 处理销售订单信息
            InventoryAdjustPriceRepDto saleOrderInfoRepDto = new InventoryAdjustPriceRepDto();
            try {
                BeanUtils.mapArrayToObject(inventoryAdjustPriceQueryRepDtos.getColumns().toArray(), objects.toArray(), saleOrderInfoRepDto);
            } catch (IllegalAccessException e) {
                throw new JeecgBootException(e);
            }
            inventoryAdjustPriceRepDtos.add(saleOrderInfoRepDto);
        }
        return inventoryAdjustPriceRepDtos;
    }


    @Override
    public InventoryAdjustPriceQueryRepDto inventoryAdjustPriceQuery(InventoryAdjustPriceQueryReqDto inventoryAdjustPriceQueryReqDto) {
        InventoryAdjustPriceQueryRepDto saleOrderQueryRepDtos = new InventoryAdjustPriceQueryRepDto();
        if (CollectionUtils.isEmpty(inventoryAdjustPriceQueryReqDto.getSelectFields())) {
            // 构建销售订单查询字段
            List<String> selectFields = ReflectUtils.getFieldsByAnnotation(InventoryAdjustPriceInfoReqDto.class);
            inventoryAdjustPriceQueryReqDto.setSelectFields(selectFields);
        }
        String postUrl = T_PLUS_URL + "/tplus/api/v2/InventoryAdjustPriceOpenApi/FindVoucherList";
        String result = HttpUtils.sendPost(postUrl, JsonUtils.bean2Json(inventoryAdjustPriceQueryReqDto), initRequestToken());
        if (StringUtils.isNotBlank(result)) {
            // 请求超时或其他接口调用异常时时返回{"code":999,"message": "请求超时"}
            // 而正常请求时又是直接返回List对象,所以用try捕获异常处理
            try {
                InventoryAdjustPriceListRepDto saleOrderListRepDto = JsonUtils.json2bean(result, InventoryAdjustPriceListRepDto.class);
                if (saleOrderListRepDto != null && Objects.equals(saleOrderListRepDto.getCode(), "0")) {
                    saleOrderQueryRepDtos = saleOrderListRepDto.getData();
                }
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return null;
            }
        }
        return saleOrderQueryRepDtos;
    }
}
